import { ElMessage } from "element-plus";

/**
 * 表格隔行变色
 * @param rowIndex
 * @return {string}
 */
export const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? "even-row" : "odd-row";
};

/**
 * 随机生成ID
 * @return {string}
 */
export const generateId = () => {
  const str = [];
  const hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    str[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  str[14] = "4";
  str[19] = hexDigits.substr((str[19] & 0x3) | 0x8, 1);
  return str.join("");
};

/**
 * 滚动到指定元素底部
 */
export const scrollToBottom = id => {
  const el = document.getElementById(id);
  const scrollHeight = el?.scrollHeight ?? 0;
  el.scrollTo({
    top: scrollHeight,
    behavior: 'smooth'
  });
};

/**
 * 复制
 * @param value
 */
export const handelCopy = value => {
  const textarea = document.createElement("textarea");
  textarea.setAttribute("id", "copyTextarea");
  textarea.value = `editorCopy-${value}`;
  // textarea.value = `$\{${value}}`;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("Copy") && ElMessage.success("复制成功");
  document.body.removeChild(textarea);
};
/**
 * 拿到文件流后的下载的方法
 * @param {*} data
 * @param {*} filename
 * @param {*} mime
 * @param {*} bom
 */
export function downloadByData(data, filename) {
  console.log(data);
  const blobData =  [data];
  const blob = new Blob(blobData, { type: 'application/octet-stream' });
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(blob, filename+'.doc');
  } else {
    const blobURL = window.URL.createObjectURL(blob);
    console.log(blobURL);
    const tempLink = document.createElement('a');
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    tempLink.setAttribute("download", filename + ".doc");
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank');
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    window.URL.revokeObjectURL(blobURL);
  }
}